/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.TCC_NOVO.client.componente;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Position;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.event.GridCellListenerAdapter;
import com.gwtext.client.widgets.layout.ColumnLayoutData;
import java.util.ArrayList;
import org.TCC_NOVO.client.GWTServiceAsync;
import org.TCC_NOVO.client.comando.Comando;
import org.TCC_NOVO.client.modelo.Slide;

/**
 *
 * @author Emerson
 */
public class FrTemplateSlide extends Window {

    GridPanel gridTemplate;
    Store storeTemplate;
    RecordDef recordDefTemplate;
    private final GWTServiceAsync controller;
    Comando carregarTemplateSelecionado = null;

    public FrTemplateSlide(GWTServiceAsync controller, Comando carregarTemplateSelecionado) {
        this.controller = controller;
        this.carregarTemplateSelecionado = carregarTemplateSelecionado;
        init();
    }

    private void init(){
        this.add(getPanel(), new ColumnLayoutData(1));
        carregarTemplates();
        this.setTitle("Template de slides");
        this.setButtonAlign(Position.LEFT);
        this.setBorder(false);
        this.setPaddings(1);
        this.setBorder(false);
        this.setSize(200, 370);
        this.setResizable(false);
        this.setModal(true);
    }

    private void carregarTemplates() {
        controller.getListaTemplateSlide(new CallbackCarregarTemplate());
    }

    private class CallbackCarregarTemplate implements AsyncCallback<ArrayList<Slide>> {
        @Override
        public void onSuccess(ArrayList<Slide> result) {
            loadRecord(result);
        }

        @Override
        public void onFailure(Throwable caught) {
            MessageBox.alert("Erro ", caught.getMessage());
        }
     }

    private Panel getPanel() {
        Panel panel = new Panel();
        panel.setFrame(true);
        panel.add(getPanelSlide());

        Button carregarTemplateButton = new Button();
        carregarTemplateButton.setText("Carregar");
        carregarTemplateButton.setTooltip("Carregar");
        carregarTemplateButton.addListener(new ButtonListenerAdapter() {
            @Override
            public void onClick(Button button, EventObject e) {
                if (gridTemplate.getSelectionModel().getSelected() == null) {
                    MessageBox.alert("Necessário Selecionar Algum Registro! ");
                } else {
                    abrirTemplate();
                }
            }
        });
        panel.addButton(carregarTemplateButton);


        Button botaoExcluir = new Button();
         botaoExcluir.setText("Excluir");
         botaoExcluir.setTooltip("Excluir slide da grid o item selecionado");
         botaoExcluir.addListener(new ButtonListenerAdapter(){
            public void onClick(Button button, EventObject e){
                if (gridTemplate.getSelectionModel().getSelected() == null){
                    MessageBox.alert("Necessário Selecionar Algum Registro! ");
                }else {
                    MessageBox.confirm("Confirmação de Exclusão", "Deseja Realmente Remover o Registro?", new MessageBox.ConfirmCallback(){
                    public void execute(String btnID){
                        if (btnID.equals("yes")){
                            removeSlide();
                        }
                    }});
                }
            }
        });

        panel.addButton(botaoExcluir);
        return panel;
    }

    private Panel getPanelSlide() {
        recordDefTemplate = new RecordDef(new FieldDef[]{
                    new IntegerFieldDef("id"),
                    new StringFieldDef("referencia"),
                    new StringFieldDef("conteudo")
                });

        storeTemplate = new Store(recordDefTemplate);

        gridTemplate = new GridPanel();
        gridTemplate.setStore(storeTemplate);

        ColumnConfig[] columnsObj = new ColumnConfig[]{
            new ColumnConfig("Slides", "referencia", 175, true)
        };

        ColumnModel columnModel = new ColumnModel(columnsObj);
        gridTemplate.setColumnModel(columnModel);
        gridTemplate.setFrame(true);
        gridTemplate.setStripeRows(true);
        gridTemplate.setSize(175, 300);
        gridTemplate.addGridCellListener(new GridCellListenerAdapter() {

            @Override
            public void onCellDblClick(GridPanel grid, int rowIndex, int colIndex, EventObject e) {
                abrirTemplate();
            }
        });
        return gridTemplate;
    }

    public Slide getTemplateSelecionado() {
        Slide slide = new Slide();
        slide.setId(gridTemplate.getSelectionModel().getSelected().getAsInteger("id"));
        slide.setReferencia(gridTemplate.getSelectionModel().getSelected().getAsString("referencia"));
        slide.setConteudo(gridTemplate.getSelectionModel().getSelected().getAsString("conteudo"));
        return slide;
    }

    public void addRecordSlide(Slide slide) {
        Object[] rowData = new Object[]{
            slide.getId(),
            slide.getReferencia(),
            slide.getConteudo(),};
        Record recordLoc = recordDefTemplate.createRecord(rowData);
        storeTemplate.add(recordLoc);
    }

    private void removeSlide() {
        Slide slide = new Slide();
        slide.setId(gridTemplate.getSelectionModel().getSelected().getAsInteger("ID"));
        controller.removerTemplateSlide(slide, new CallbackExluirTemplate());
    }

    private class CallbackExluirTemplate implements AsyncCallback<Boolean> {
        @Override
            public void onSuccess(Boolean result) {
                if(result){
                    storeTemplate.remove(gridTemplate.getSelectionModel().getSelected());
                }
            }

            @Override
            public void onFailure(Throwable caught) {
                MessageBox.alert("Erro ", caught.getMessage());
            }
     }

    private void loadRecord(ArrayList<Slide> listaSlide) {
        //preenche o grid com as atividades daquele roteiro
        for (Slide slide : listaSlide) {
            addRecordSlide(slide);
        }
    }

    private void abrirTemplate() {
        Slide template = new Slide();
        template.setReferencia(gridTemplate.getSelectionModel().getSelected().getAsString("referencia"));
        template.setConteudo(gridTemplate.getSelectionModel().getSelected().getAsString("conteudo"));
        carregarTemplateSelecionado.executar(template);
        FrTemplateSlide.this.hide();
    }
}
